
// https://leetcode.cn/problems/longest-increasing-path-in-a-matrix/description/

class Solution
{
    int res = 1;
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    int m, n;

public:
    int longestIncreasingPath(vector<vector<int>>& matrix)
    {
        m = matrix.size();
        n = matrix[0].size();
        vector<vector<int>> lens(m, vector<int>(n, -1));
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                res = max(res, dfs(i, j, matrix, lens));
        return res;
    }

    int dfs(int i, int j, vector<vector<int>>& grid, vector<vector<int>>& lens)
    {
        if (lens[i][j] != -1)
            return lens[i][j];

        int max_len = 1;
        for (int k = 0; k < 4; ++k)
        {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > grid[i][j])
                max_len = max(max_len, dfs(x, y, grid, lens) + 1);
        }
        lens[i][j] = max_len;
        return max_len;
    }
};